import {
  CanActivate,
  ExecutionContext,
  Injectable,
  UnauthorizedException,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import constant from 'src/config/Constant';
import { Request } from 'express';
import { Reflector } from '@nestjs/core';
import { PUBLIC_ROUTE } from 'src/decorations/PublicRoute';
import { CreateUserDto } from 'src/server/user/dto/create-user.dto';
import { RedisServer } from 'src/config/Redis';
import Utils from 'src/utils/Utils';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(
    private jwtService: JwtService,
    private reflector: Reflector,
    private redisServer: RedisServer,
  ) { }

  async canActivate(context: ExecutionContext): Promise<boolean> {
    if (this.doPublicRoute(context)) {
      // 无需路由权限
      return true;
    }
    const request = context.switchToHttp().getRequest();
    const token = this.extractTokenFromHeader(request);
    if (!token) {
      throw new UnauthorizedException('抱歉！您未登录，无法访问~');
    }
    let guid = '';
    try {
      const payload = (await this.jwtService.verifyAsync(token, {
        secret: constant.jwt.secret,
      })) as CreateUserDto;
      // 挂载解密信息
      request['userinfo'] = payload;
      guid = payload.guid;
    } catch {
      throw new UnauthorizedException('抱歉！您的登录信息已失效~');
    }
    let result = '';
    try {
      const redis = await this.redisServer.getClient();
      result = await redis.get(Utils.redisTokenKey(guid));
    } catch {
      throw new UnauthorizedException('Redis 连接异常~');
    }
    if (!result) {
      throw new UnauthorizedException('抱歉！您的登录信息已过期~');
    }
    return true;
  }

  private extractTokenFromHeader(request: Request): string | undefined {
    const [type, token] = request.headers.authorization?.split(' ') ?? [];
    return type === 'Bearer' ? token : undefined;
  }

  // API 权限认证
  private doPublicRoute(context: ExecutionContext) {
    const publicRoute = this.reflector.getAllAndOverride<boolean>(
      PUBLIC_ROUTE,
      [context.getHandler(), context.getClass()],
    );
    // true 无需登陆
    // false 需登陆
    return publicRoute;
  }
}
